/* $Id: HibernateUtil.java 120 2011-08-23 09:01:22Z altdotua@gmail.com $ */

package alt.djudge.frontend.server;

import java.io.Serializable;
import java.sql.Statement;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import alt.djudge.frontend.server.datatypes.AbstractEntry;


public class HibernateUtil
{
	private static final Logger log = Logger.getLogger(HibernateUtil.class);

	private static final SessionFactory sessionFactory;

	static
	{
		if (!Deployment.isGAE())
		{
			try
			{
				// TODO: drop me
				BasicConfigurator.configure();
				// Create the SessionFactory from hibernate.cfg.xml
				sessionFactory = new Configuration().configure()
						.buildSessionFactory();
			}
			catch (Throwable ex)
			{
				// Make sure you log the exception, as it might be swallowed
				log.fatal("Initial SessionFactory creation failed. ", ex);
				throw new ExceptionInInitializerError(ex);
			}
		}
		else
		{
			sessionFactory = null;
		}
	}

	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public static void saveOrUpdateObject(Object object)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(object);
		session.getTransaction().commit();
	}

	public static boolean deleteObject(Object object)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.delete(object);
		session.getTransaction().commit();
		return true;
	}

	public static AbstractEntry loadObject(
			Class<? extends AbstractEntry> objectClass, Serializable objectId)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		AbstractEntry result = (AbstractEntry) session.load(objectClass,
				objectId);
		session.getTransaction().commit();
		return result;
	}

	@SuppressWarnings({ "rawtypes" })
	public static List loadObjects(Class objectClass)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List result = session.createQuery(
				"from " + objectClass.getSimpleName() + " order by name")
				.list();
		session.getTransaction().commit();
		return result;
	}
	
	@SuppressWarnings("deprecation")
	public static boolean executeSql(String sql)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction transaction = session.beginTransaction();
		try
		{
			Statement statement = session.connection().createStatement();
			statement.execute(sql);
			transaction.commit();
			return true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			log.error("statement.execute:\n" + sql, e);
		}
		finally
		{
			if (transaction.isActive())
				transaction.rollback();
		}
		return false;
	}
}